import os
import re


def replace_in_file(file_path, old_str, new_str):
    """替换文件中的字符串"""
    with open(file_path, 'r', encoding='utf-8') as file:
        content = file.read()

    # 使用正则表达式替换所有匹配的字符串
    new_content = re.sub(re.escape(old_str), new_str, content)

    with open(file_path, 'w', encoding='utf-8') as file:
        file.write(new_content)


def batch_replace_in_directory(directory, old_str, new_str, file_extension):
    """批量替换目录下指定扩展名文件中的字符串"""
    for root, _, files in os.walk(directory):
        for file in files:
            if file.endswith(file_extension):
                file_path = os.path.join(root, file)
                replace_in_file(file_path, old_str, new_str)
                print(f"已替换文件: {file_path}")


if __name__ == "__main__":
    # 设置目录路径、旧字符串、新字符串和文件扩展名
    directory = "downloaded_files"  # 替换为你的目录路径
    old_str = "net.xdob"
    new_str = "org"
    file_extension = ".pom"

    # 执行批量替换
    batch_replace_in_directory(directory, old_str, new_str, file_extension)
